﻿<%@ WebHandler Language="C#" Class="ContainerCommissioningHandler" %>

/*Description: 质量提起处理程序
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:2022-10-08
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Collections;
using System.Net;
using System.IO;
using System.Text;
using System.Xml;
using BusinessRule.Common;
using System.Linq;

public class ContainerCommissioningHandler : IHttpHandler, IRequiresSessionState
{

    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    uLMSCommissioningBusiness commissionBusiness = new uLMSCommissioningBusiness();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "数据过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "GetContainerListForOut": //查询批次主数据（外包转出）
                    GetContainerListForOut(context);
                    break;
                case "GetContainerDetailListForOut": //查询批次详细数据（外包转出）
                    GetContainerDetailListForOut(context);
                    break;
                case "GetContainerCommissionForOut": //获取批次外委数据（外包转出）
                    GetContainerCommissionForOut(context);
                    break;
                case "GetContainerListForTemp": //查询批次主数据（临时申请）
                    GetContainerListForTemp(context);
                    break;
                case "GetContainerDetailListForTemp": //查询批次详细数据（临时申请）
                    GetContainerDetailListForTemp(context);
                    break;
                case "GetContainerCommissionForTemp": //获取批次外委数据（临时申请）
                    GetContainerCommissionForTemp(context);
                    break;
                case "SaveCommissionOutData": //转出保存（外包转出）
                    SaveCommissionOutData(context);
                    break;
                case "SaveCommissionTempData": //保存临时申请
                    SaveCommissionTempData(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
    /// <summary>
    /// 查询批次主数据
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerListForOut(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("ScanContainerName", context.Request["scanContainer"].ToString());
        if (!string.IsNullOrWhiteSpace(para["ScanContainerName"].ToString()))
        {
            para["ScanContainerName"] = commonBusiness.ContainerScan(para["ScanContainerName"].ToString());
        }
        para.Add("ScanOrderName", context.Request["scanOrder"].ToString());
        para.Add("ProductName", context.Request["productName"].ToString());
        para.Add("ContainerName", context.Request["containerName"].ToString());
        para.Add("StepName", context.Request["stepName"].ToString());
        para.Add("PageSize", context.Request["pageSize"].ToString());
        para.Add("PageIndex", context.Request["pageIndex"].ToString());
        para.Add("Status", context.Request["status"].ToString());
        uMESProcessResult result = commissionBusiness.GetContainerCommissioningOutList(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询详细批次
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerDetailListForOut(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("OrderNo", context.Request["MFGORDERNAME"].ToString());
        para.Add("ProductId", context.Request["PRODUCTID"].ToString());
        para.Add("Togetherflag", context.Request["TOGETHERFLAG"].ToString());
        para.Add("ContainerNo", context.Request["CONTAINERNO"].ToString());
        para.Add("WorkflowID", context.Request["WORKFLOWID"].ToString());
        para.Add("WorkflowStepId", context.Request["WORKFLOWSTEPID"].ToString());
        result.DBTable = commissionBusiness.GetContainerCommissioningOutDetailList(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 查询批次主数据（临时外委）
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerListForTemp(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("ScanContainerName", context.Request["scanContainer"].ToString());
        if (!string.IsNullOrWhiteSpace(para["ScanContainerName"].ToString()))
        {
            para["ScanContainerName"] = commonBusiness.ContainerScan(para["ScanContainerName"].ToString());
        }
        para.Add("ScanOrderName", context.Request["scanOrder"].ToString());
        para.Add("ProductName", context.Request["productName"].ToString());
        para.Add("ContainerName", context.Request["containerName"].ToString());
        para.Add("StepName", context.Request["stepName"].ToString());
        para.Add("PageSize", context.Request["pageSize"].ToString());
        para.Add("PageIndex", context.Request["pageIndex"].ToString());
        uMESProcessResult result = commissionBusiness.GetContainerCommissioningTempList(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询详细批次（临时外委）
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerDetailListForTemp(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("OrderNo", context.Request["MFGORDERNAME"].ToString());
        para.Add("ProductId", context.Request["PRODUCTID"].ToString());
        para.Add("Togetherflag", context.Request["TOGETHERFLAG"].ToString());
        para.Add("ContainerNo", context.Request["CONTAINERNO"].ToString());
        para.Add("WorkflowID", context.Request["WORKFLOWID"].ToString());
        para.Add("WorkflowStepId", context.Request["WORKFLOWSTEPID"].ToString());
        result.DBTable = commissionBusiness.GetContainerCommissioningTempDetailList(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取批次外委数据（临时外委）
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerCommissionForTemp(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable paramDt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (paramDt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "没有选择批次" }));
            return;
        }
        //查询批次可外委的工序
        string sql = @"
SELECT ws.workflowstepname,ws.workflowstepid,s.specno,s.opdesc,ws.sequence FROM Workflowstep ws
left join specbase sb on sb.specbaseid = ws.specbaseid 
left join spec s on s.specid = nvl(sb.revofrcdid,ws.specid)  
WHERE ws.sequence >= {0} AND ws.workflowid = '{1}' AND nvl(nvl(ws.CONTROLCODE,S.CONTROLCODE),'1') <> 'LY05' and S.FACTORYID = '{2}' {3}
AND NOT EXISTS (SELECT 1 FROM containerstepnoship css WHERE css.workflowstepid=ws.workflowstepid AND css.containerid in ({4}) AND css.isuse = 0 AND css.noship = 2)
AND NOT EXISTS (SELECT 1 FROM containerstepdispatch csd WHERE csd.workflowstepid=ws.workflowstepid AND csd.containerid in ({4}) AND csd.isuse = 0)
AND NOT EXISTS (SELECT 1 FROM ContainerCommiDetail ccd WHERE ccd.workflowstepid=ws.workflowstepid AND ccd.containerid in ({4}) AND ccd.isuse = 0)";
        string containerIDs = "";
        foreach (DataRow item in paramDt.Rows)
        {
            containerIDs += string.Format("'{0}',", item["ContainerID"].ToString());
        }
        containerIDs = containerIDs.TrimEnd(',');
        string isCheckStr = "";
        if (commonBusiness.GetFatoryAttributes(m_UserInfo.FactoryID, "检验序自动报工") == "是")
        {
            isCheckStr = "AND NVL(S.LASTCHECK,'0') <> '1'";
        }
        sql = string.Format(sql, paramDt.Rows[0]["sequence"].ToString(), paramDt.Rows[0]["workflowid"].ToString(),
                            m_UserInfo.FactoryID, isCheckStr, containerIDs);
        sql += " ORDER BY ws.sequence";
        DataTable dtCommission = DatabaseHelper.Query_ReturnDatTable(sql);
        dtCommission.TableName = "dtCommission";
        result.DBDataSet.Tables.Add(dtCommission);
        //获取采购组
        ExcuteEntity exuteEntity = new ExcuteEntity("PurchaseOrganize", ExcuteEntity.ExcuteTypeEnum.selectAll);
        exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("FactoryCode", m_UserInfo.FactoryCode, FieldEntity.FieldTypeEnum.Str) };
        DataTable dtPurchase = DatabaseHelper.QueryDataByEntity(exuteEntity);
        dtPurchase.TableName = "dtPurchase";
        result.DBDataSet.Tables.Add(dtPurchase);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取批次外委数据（外委转出）
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerCommissionForOut(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable paramDt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (paramDt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "没有选择批次" }));
            return;
        }
        string status = context.Request["status"].ToString();
        string sql = @"
                    SELECT * FROM (
                    SELECT Distinct cc.containercommissioningid,cci.containerid,cci.containername,ws.workflowstepname,ct.customername,e.fullname outfullname
                    ,s.specno,s.opdesc,ccd.containercommidetailid,ws.sequence
                    FROM containercommissioning cc
                    LEFT JOIN containercommiDetail ccd ON ccd.containercommissioningid = cc.containercommissioningid
                    LEFT JOIN containercurrentinfo cci ON cci.containerid = cc.containerid
                    LEFT JOIN Workflowstep ws ON ws.workflowstepid = ccd.workflowstepid
                    left join specbase sb on sb.specbaseid = ws.specbaseid 
                    left join spec s on s.specid = nvl(sb.revofrcdid,ws.specid) 
                    LEFT JOIN customer ct ON ct.customerid = cc.outcustomerid
                    LEFT JOIN employee e ON e.employeeid = cc.outemployeeid
                    where ";
        if (status == "1") //待转出
        {
            sql += " cc.outdate IS NULL and (";
        }
        else if (status == "2") //待审核
        {
            sql += " cc.outdate IS NOT NULL AND cc.outsourcoutno IS NULL and (";
        }
        else //已转出
        {
            sql += " cc.outdate IS NOT NULL AND cc.outsourcoutno IS NOT NULL AND cc.IsSendScm = 1 and (";
        }
        foreach (DataRow item in paramDt.Rows)
        {
            sql += string.Format(" (cc.containerid = '{0}' AND cc.isuse = 0) or", item["ContainerID"].ToString());
        }
        sql = sql.TrimEnd('r').TrimEnd('o') + ")";
        sql += ") ORDER BY containerid,sequence";
        DataTable dtCommission = DatabaseHelper.Query_ReturnDatTable(sql);
        dtCommission.TableName = "dtCommission";
        result.DBDataSet.Tables.Add(dtCommission);
        //获取外委厂家
        //DataTable dtCustom = commissionBusiness.GetCustomerInfo();
        //dtCustom.TableName = "dtCustom";
        //result.DBDataSet.Tables.Add(dtCustom);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存临时外委数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveCommissionTempData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "申请成功" };
        DataTable containerDt = JsonConvert.DeserializeObject<DataTable>(context.Request["containerDt"].ToString());//所选批次
        DataTable stepDt = JsonConvert.DeserializeObject<DataTable>(context.Request["stepDt"].ToString());//所选工序
        if (containerDt.Rows.Count == 0 || stepDt.Rows.Count == 0)
        {
            result.Result = false; result.Message = "没有选择数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string purchaseCode = context.Request["purchaseCode"].ToString();//采购组码
        string purchaseName = context.Request["purchaseName"].ToString();//采购组名称
        if (string.IsNullOrWhiteSpace(purchaseCode))
        {
            result.Result = false; result.Message = "请选择采购组";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string containerIDs = string.Empty;//获取所选批次的ID集合串
        containerDt.AsEnumerable().ToList().ForEach(p =>
        {
            containerIDs += string.Format("'{0}',", p["CONTAINERID"].ToString());
        });
        containerIDs = containerIDs.TrimEnd(',');
        //获取申请的工序序号列表
        List<int> list_swquence = new List<int>();
        string selectAps = "SELECT 1 FROM apsplandetail ap WHERE ap.containerid IN ({0}) AND ap.workflowstepname = '{1}' AND ap.status = '1'";//验证工序是否下发派工
        foreach (DataRow item in stepDt.Rows)
        {
            if (DatabaseHelper.GetSingle(string.Format(selectAps, containerIDs, item["WorkflowStepName"].ToString())) != null)
            {
                result.Result = false; result.Message = string.Format("所选工序：{0}存在排产下发，无法进行临时外委。", item["WorkflowStepName"].ToString());
                break;
            }
            list_swquence.Add(int.Parse(item["sequence"].ToString()));
        }
        if (!result.Result)
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        list_swquence.Sort();
        int firstSeq = list_swquence[0];
        int lastSeq = list_swquence[list_swquence.Count - 1] + 1;
        if (lastSeq - firstSeq > list_swquence.Count)
        {
            result.Result = false; result.Message = "只能选择连续的工序进行外委";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        Dictionary<string, string> dic = new Dictionary<string, string>();
        //查询工艺下的所有工序，获取外委第一个工序，和转入工序
        DataTable workfowstepDt = commonBusiness.GetWorkFlowSetpsByWorkflowID(containerDt.Rows[0]["workflowid"].ToString());
        DataRow[] drs = workfowstepDt.Select("sequence=" + firstSeq + "");
        if (drs.Length == 0)
        {
            result.Result = false; result.Message = "数据有误";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        dic.Add("WorkflowStepID", drs[0]["WorkflowStepID"].ToString());
        DataRow[] drl = workfowstepDt.Select("sequence=" + lastSeq + "");
        if (drl.Length == 0)
        {
            result.Result = false; result.Message = "外委序不能是最后一道序";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        dic.Add("InWorkflowStepID", drl[0]["WorkflowStepID"].ToString());
        dic.Add("PurchaseCode", purchaseCode);
        dic.Add("PurchaseName", purchaseName);
        dic.Add("EmployeeID", m_UserInfo.EmployeeID.ToString());
        dic.Add("EmployeeName", m_UserInfo.FullName.ToString());
        dic.Add("FactoryID", m_UserInfo.FactoryID);
        dic.Add("Type", dic["WorkflowStepID"] == containerDt.Rows[0]["WorkflowStepID"].ToString() ? "1" : "2");//外委序是否包含当前序
        commissionBusiness.SaveContainerTempCommiData(dic, containerDt, stepDt);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存外委转出
    /// </summary>
    /// <param name="context"></param>
    public void SaveCommissionOutData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable paramDt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());//所选外委工序
        if (paramDt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "没有选择外委工序" }));
            return;
        }
        string orderName = context.Request["orderName"].ToString();//生产订单号
        string needCompletedDate = context.Request["needCompletedDate"].ToString();//要求回厂日期
        string outWeight = context.Request["outWeight"].ToString();//单件重量
        string unitQuanity = context.Request["unitQuanity"].ToString();//单台数
        result = GetErpSendDatasToDatatable(orderName);//获取Erp生产订单采购数据
        if (!result.Result)
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        DataTable dtErpStep = result.DBTable;
        if (dtErpStep.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未获取到Erp生产订单采购数据！" }));
            return;
        }
        DataRow drErp = dtErpStep.Rows[0];
        if (string.IsNullOrWhiteSpace(drErp["OutsourcOrder"].ToString()))
        {
            result.Result = false;
            result.Message = "ERP采购订单参数中没有采购订单号";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (string.IsNullOrWhiteSpace(drErp["OutsourcPactNo"].ToString()))
        {
            result.Result = false;
            result.Message = "ERP采购订单参数中没有采购合同号";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (string.IsNullOrWhiteSpace(drErp["OutsourcPactValidDate"].ToString()))
        {
            result.Result = false;
            result.Message = "ERP采购订单参数中没有采购合同有效日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (string.IsNullOrWhiteSpace(drErp["LIFNR"].ToString()))
        {
            result.Result = false;
            result.Message = "ERP采购订单参数中没有供应商编号";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (string.IsNullOrWhiteSpace(drErp["LNAME"].ToString()))
        {
            result.Result = false;
            result.Message = "ERP采购订单参数中没有供应商名称";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (string.IsNullOrWhiteSpace(drErp["BEDAT"].ToString()))
        {
            result.Result = false;
            result.Message = "ERP采购订单参数中没有凭证日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (DateTime.Now > DateTime.Parse(drErp["OutsourcPactValidDate"].ToString()))
        {
            result.Result = false;
            result.Message = "合同有效期小于转出日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //处理erp推送工序和选择的工序进行判断
        ArrayList sqlList = new ArrayList();//保存更新Sql
        //        string containerCommissioningIDs = "";
        //        foreach (DataRow item in paramDt.Rows)
        //        {
        //            containerCommissioningIDs += "'" + item["containerCommissioningID"] + "',";
        //        }
        //        containerCommissioningIDs = containerCommissioningIDs.TrimEnd(',');
        //        //获取所有的外委工序明细
        //        string strSql = @"SELECT ccd.*,s.specno,s.opdesc,ws.workflowstepname stepname FROM ContainerCommiDetail ccd
        //                          LEFT JOIN Workflowstep ws ON ws.workflowstepid = ccd.workflowstepid
        //                          left join specbase sb on sb.specbaseid = ws.specbaseid 
        //                          left join spec s on s.specid = nvl(sb.revofrcdid,ws.specid)
        //                          where ccd.containercommissioningid in (" + containerCommissioningIDs + ")";
        //        DataTable dtdetail = DatabaseHelper.Query_ReturnDatTable(strSql);
        foreach (DataRow item in paramDt.Rows)
        {
            DataRow[] drs = dtErpStep.Select("SpecNo='" + item["specno"].ToString() + "' and SpecDesc='" + item["opdesc"].ToString() + "'");
            if (drs.Length == 0)
            {
                result.Result = false;
                result.Message = "采购订单中没有(" + item["workflowstepname"].ToString() + ")工序";
                break;
            }
            //更新外委子表的采购订单行号
            sqlList.Add(string.Format(@"UPDATE ContainerCommiDetail ccd SET ccd.outsourcorderrownum = '{0}' 
                                        WHERE ccd.containercommidetailid = '{1}'", drs[0]["OutsourcOrderRowNum"].ToString(),
                                        item["containercommidetailid"].ToString()));
        }
        if (result.Result)
        {
            DataTable dtMain = paramDt.DefaultView.ToTable(true, "containercommissioningid");
            //更新外委主表
            foreach (DataRow item in dtMain.Rows)
            {
                sqlList.Add(string.Format(@"UPDATE containercommissioning cc SET cc.outsourcorder='{0}', 
                                            cc.outsourcpactno='{1}', cc.outsourcpactvaliddate = to_date('{2}','yyyy-MM-dd'),
                                            cc.LIFNR = '{3}',cc.LNAME = '{4}',cc.BEDAT=to_date('{5}','yyyy-MM-dd'),cc.outdate = sysdate,cc.outemployeeid='{6}',
                                            cc.needcompletedate=to_date('{7}','yyyy-MM-dd'),cc.out_weight='{8}',cc.unit_quanity='{9}'
                                            WHERE cc.containercommissioningid = '{10}'", drErp["OutsourcOrder"].ToString(),//采购订单号
                                             drErp["OutsourcPactNo"].ToString(),//采购合同号
                                             drErp["OutsourcPactValidDate"].ToString(),//采购合同有效日期
                                             drErp["LIFNR"].ToString(),//供应商编号
                                             drErp["LNAME"].ToString(),//供应商名称
                                             drErp["BEDAT"].ToString(),//凭证日期
                                             m_UserInfo.EmployeeID.ToString(),//转出人
                                             needCompletedDate, outWeight, unitQuanity,//要求返厂日期，单件重量，单台数
                                             item["containercommissioningid"].ToString()));//主ID
            }
            result.Result = DatabaseHelper.ExecuteSqlListTran(sqlList);
        }
        result.Message = result.Result ? "转出成功" : result.Message;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private uMESProcessResult GetErpSendDatasToDatatable(string orderName)
    {
        //string param = "strMessage=" + orderName + "";//参数
        //byte[] bs = Encoding.UTF8.GetBytes(param);
        //HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost/TCWebService/TCMTOMESservice.asmx/ERP_Send_Nonconforming_Service");
        //req.Method = "post";
        //req.ContentType = "application/x-www-form-urlencoded";
        //req.ContentLength = bs.Length;
        //using (Stream reqStream = req.GetRequestStream())
        //{
        //    reqStream.Write(bs, 0, bs.Length);
        //    reqStream.Close();
        //}
        //WebResponse wr;
        //try
        //{
        //    wr = (HttpWebResponse)req.GetResponse();
        //}
        //catch (WebException ex)
        //{
        //    wr = (HttpWebResponse)ex.Response;
        //}
        //Stream sr = wr.GetResponseStream();
        //StreamReader reader = new StreamReader(sr, Encoding.UTF8);
        //string res = reader.ReadToEnd();

        uMESProcessResult res = new uMESProcessResult() { Result = true };
        //MESGetErpSourcOrder.PS_SAPServicesHttpService sap = new MESGetErpSourcOrder.PS_SAPServicesHttpService();
        //MESGetErpSourcOrder.ErpAndAppSyncData mm = new MESGetErpSourcOrder.ErpAndAppSyncData();
        //mm.ReqMsg = GetXMLForErpOutSourc(orderName);

        //MESGetErpSourcOrder.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
        //LogHelp.WriteLog("返回的消息：" + result.RespMsg);
        string exxml = "";//result.RespMsg;
        //解析返回的xml字符串，放入datatable
        DataTable dtErpStep = new DataTable(); //erp获取的可外委工序
        dtErpStep.Columns.Add("OutsourcOrder");//采购订单号
        dtErpStep.Columns.Add("OutsourcOrderRowNum");//采购订单行号
        dtErpStep.Columns.Add("OutsourcPactNo");//采购合同号
        dtErpStep.Columns.Add("OutsourcPactValidDate");//采购合同有效日期
        dtErpStep.Columns.Add("MfgOrderName");//订单号
        dtErpStep.Columns.Add("ProductName");//件号
        dtErpStep.Columns.Add("PlanQty");//计划数
        dtErpStep.Columns.Add("SpecNo");//工序号
        dtErpStep.Columns.Add("SpecDesc");//工序名称
        dtErpStep.Columns.Add("SonSpecNo");//子工序号
        dtErpStep.Columns.Add("SonSpecDesc");//子工序名称
        dtErpStep.Columns.Add("LIFNR");//供应商编号
        dtErpStep.Columns.Add("LNAME");//供应商名称
        dtErpStep.Columns.Add("BEDAT");//凭证日期

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(exxml);
        res.Result = bool.Parse(doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText);//是否成功
        res.Message = "ERP反馈：" + doc.SelectSingleNode("RespMsg/header/message").InnerText;//返回的消息
        if (!res.Result)
        {
            return res;
        }
        XmlDocument docItem = new XmlDocument();
        docItem.LoadXml("<Res>" + doc.SelectSingleNode("RespMsg/document").InnerText + "</Res>");//返回的CDATA中存在多个根节点，需要在外面加一个节点包围
        string rType = docItem.SelectSingleNode("Res/OUTTYP/RTYPE").InnerText;
        if (rType != "S")//调用方法失败
        {
            res.Result = false;
            res.Message = "ERP反馈：" + docItem.SelectSingleNode("Res/OUTTYP/RTMSG").InnerText;
            return res;
        }
        XmlNode xn = docItem.SelectSingleNode("Res/ITEMS");
        XmlNodeList xnlist = xn.ChildNodes;
        foreach (XmlNode item in xnlist)
        {
            DataRow dr = dtErpStep.NewRow();
            foreach (XmlNode node in item.ChildNodes)
            {
                switch (node.Name)
                {
                    case "EPIBOLYORDERNO"://采购订单号
                        dr["OutsourcOrder"] = node.InnerText;
                        break;
                    case "UTSOURCORDERROWNUM"://采购订单行号
                        dr["OutsourcOrderRowNum"] = node.InnerText;
                        break;
                    case "MFGORDERNAME"://订单号
                        dr["MfgOrderName"] = node.InnerText;
                        break;
                    case "PRODUCTNAME": //件号
                        dr["ProductName"] = node.InnerText;
                        break;
                    case "SPECNO"://工序号
                        dr["SpecNo"] = node.InnerText;
                        break;
                    case "SPECDESC"://工序名称
                        dr["SpecDesc"] = node.InnerText;
                        break;
                    case "SONSPECNO"://子序号
                        dr["SonSpecNo"] = node.InnerText;
                        break;
                    case "SONSPECDESC"://子序名称
                        dr["SonSpecDesc"] = node.InnerText;
                        break;
                    case "QTY"://数量
                        dr["PlanQty"] = node.InnerText;
                        break;
                    case "OUTSOURCPACTNO"://采购合同号
                        dr["OutsourcPactNo"] = node.InnerText;
                        break;
                    case "VALIDITYDATE"://采购合同有效日期
                        dr["OutsourcPactValidDate"] = node.InnerText;
                        break;
                    case "LIFNR"://供应商编号
                        dr["LIFNR"] = node.InnerText;
                        break;
                    case "LNAME"://供应商名称
                        dr["LNAME"] = node.InnerText;
                        break;
                    case "BEDAT"://凭证日期
                        dr["BEDAT"] = node.InnerText;
                        break;
                    default:
                        break;
                }
            }
            dtErpStep.Rows.Add(dr);
        }
        //返回本件号的数据
        res.DBTable = dtErpStep.Select(string.Format("MfgOrderName='{0}'", orderName)).CopyToDataTable();
        return res;
    }

    /// <summary>
    /// 获取调用ERP采购订单接口xml参数
    /// </summary>
    /// <param name="orderName"></param>
    /// <returns></returns>
    private string GetXMLForErpOutSourc(string orderName)
    {
        try
        {
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_ERP";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";
            extNode.AppendChild(doc.CreateElement("FunName"));
            extNode.LastChild.InnerText = "ZRFC_GXWB_PO_GET";
            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);
            XmlNode documentNode = doc.CreateElement("document");
            string strData = "<ITEMS><ITEM><AUFNR>" + orderName + "</AUFNR></ITEM></ITEMS>";
            documentNode.AppendChild(doc.CreateCDataSection(strData));

            ReqNode.AppendChild(documentNode);
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }
        catch (Exception e)
        {
            LogHelp.WriteError("采购订单ERP接口xml", e);
            return string.Empty;
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}